package com.example.courtcounter;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.menu.MenuWrapperICS;
import androidx.collection.ArraySet;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;

public class MyListActivity extends ListActivity
        implements AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener{

    private static final String TAG = "MyListActivity";

    private ArrayList<HashMap<String,String>> listItems;
    private SimpleAdapter listItemAdapter;
    private Handler handler;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        handler = new Handler(Looper.myLooper()) {

            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 9) {
                    Log.i(TAG,"handleMessage: "+msg.obj);
                    //listItems = (ArrayList<HashMap<String,String>>)msg.obj;
                    ArrayList<RateItem> listdata = (ArrayList<RateItem>)msg.obj;
                    Log.i(TAG,"handleMessage: list.size:"+listItems.size());
                    MyAdapter adapter = new MyAdapter(MyListActivity.this,R.layout.list_item,listItems);
                    setListAdapter(adapter);
                }
                super.handleMessage(msg);
            }
        };

        //准备数据项
        initListView();
        setListAdapter(listItemAdapter);
        getListView().setOnItemClickListener(this);
        getListView().setOnItemLongClickListener(this);

        //启动线程
        Thread t = new Thread(() -> {
            //获取网络数据，代回list
            try {
                Log.i(TAG, "run:正在工作。。。。。");

                Document doc = Jsoup.connect("https://chl.cn/?jinri").get();
                Elements tables = doc.getElementsByTag("table");
                Element table1 = tables.first();
                //查找行tr
                Elements rows = table1.getElementsByTag("tr");
                rows.remove(0);
                for (Element row : rows) {
                    //拆分单元格td
                    Elements tds = row.getElementsByTag("td");
                    Element td1 = tds.first();
                    Element td2 = tds.get(4);
                    String str1 = td1.text().trim();
                    String str2 = td2.text().trim();

                    Log.i(TAG, "run:币种：" + td1.text() + "价格：" + td2.text());
   //                 Log.i(TAG, "run:币种2：" + td1.html() + "价格：" + td2.html());

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("ItemTitle", str1); //标题文字
                    map.put("Price", str2);   //详细描述

                    try {
                        RateItem item = new RateItem(str1, str2);
                        retlist.add(item);
                    }catch(NumberFormatException ex){
                        continue;
                    }
                    Log.i(TAG, td1.text() + "=>" + td2.text());

                    //保存到数据库中
                    //RateItem newItem = new RateItem(str1,str2);
                    ArraySet<RateItem> dataList = new ArraySet<>();
                    dataList.add(new RateItem(str1,str2));
                }


            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            //保存—>DB
            RateManager rateManager = new RateManager(this);
            rateManager.deleteAll();
            rateManager.addAll();
            Log.i(TAG,"onCreate: save to db OK");

            //发送数据给主线程
            Message msg = handler.obtainMessage(9,retlist);
            handler.sendMessage(msg);
        });
        t.start();
    }


    private void initListView(){
        listItems = new ArrayList<HashMap<String,String>>();
        for(int i = 0;i < 10; i++){
            HashMap<String,String> map = new HashMap<String,String>();
            map.put("ItemTitle","Rate: "+i); //标题文字
            map.put("Price","detail"+i);   //详细描述
            listItems.add(map);
            
        }
        //生成适配器的Item和动态数组对应的元素
        listItemAdapter = new SimpleAdapter(this,listItems,//listItems数据源
                R.layout.list_item,//ListItem的xml布局实现
                new String[]{"ItemTitle", "Price"},
                new int[]{R.id.itemTitle, R.id.price}
        );
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView,View view,int i,long l){
        //获取当前选中行数据
        HashMap<String,String> map = (HashMap<String,String>)getListView().getItemAtPosition(i);
        String title = map.get("ItemTitle");
        String price = map.get("Price");
        Log.i(TAG,"onItemClick: Title="+title);
        Log.i(TAG,"onItemClick: price="+price);
        //Intent opencountActivity = new Intent(this,Count.class);
        //opencountActivity.putExtra("title",title);
        //opencountActivity.putExtra("Price",price);
        //startActivityForResult(opencountActivity,5);


        //删除当前选用的数据项
        //adapter.remove(map);

    }


    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
       Log.i(TAG,"onItemLongClick:长按执行");
        HashMap<String,String> map = (HashMap<String,String>)getListView().getItemAtPosition(i);
       //提示删除操作
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示").setMessage("请确定使得否删除当前数据").setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i(TAG,"onClick:对话框事件处理");
                adapter.remove(map);
            }
        }).setNegativeButton("否",null);
        builder.create().show();
        Log.i(TAG,"onItemLongClick:size="+listItems.size());
        return true;
    }
}